package com.demo.config.tus;

import lombok.extern.slf4j.Slf4j;
import me.desair.tus.server.TusFileUploadService;
import org.noear.solon.core.Props;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.time.Duration;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
@Slf4j
public class TusDirectoryExpireCleaner implements Runnable{


    private Props tusProperties;

    private TusFileUploadService tusFileUploadService;

    public TusDirectoryExpireCleaner(Props tusProperties, TusFileUploadService tusFileUploadService) {
        this.tusProperties = tusProperties;
        this.tusFileUploadService = tusFileUploadService;
    }

    //定时任务
    private static final ScheduledExecutorService SCHEDULED_EXECUTOR_SERVICE = Executors.newSingleThreadScheduledExecutor();

    @Override
    public void run() {
        final Duration expireTime =Duration.parse( tusProperties.get("expireTime"));
        log.info("tus enable clean model");
        SCHEDULED_EXECUTOR_SERVICE.schedule(() -> {
            final Path lockDir = Path.of(tusProperties.get("chunkFilePath")).resolve("locks");
            if (Files.exists(lockDir)) {
                try {
                    log.info("clean up tus locks file");
                    tusFileUploadService.cleanup();
                } catch (IOException e) {
                    throw new RuntimeException("error during clean up", e);
                }
            }
        }, expireTime.getSeconds(), TimeUnit.SECONDS);
    }
}
